#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QKeyEvent>
#include<QDebug>
#include"birdsprite.h"
#include"globalgamemsger.h"
#include"pipesprite.h"
#include<QAudioFormat>
#include<QAudioDeviceInfo>
#include<QAudioInput>
#include<QtMath>
#include<QMediaPlayer>
#include<QMediaPlaylist>
//#include<QSound>
//#include<QAudioFormat>
//#include<QAudioDeviceInfo>
//#include<QAudioInput>
//#include<QAudioOutput>
const char*noteName[]={"A","A#","B","C","C#","D","D#","E","F","F#","G","G#"};
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow),pyin(SAMPLE_RATE),running(0)
{
    setWindowTitle("Press S or D to start");
    globalTicker.start(17);

    scene.setSceneRect(QRectF(0,0,Width,Height));
    scene.Init();
    this->resize(Width,Height);

    connect(&globalTicker,&QTimer::timeout,this,&MainWindow::tick);
    connect(&globalTicker,&QTimer::timeout,&scene,&QGraphicsScene::advance);

    audioDevice.open(QIODevice::ReadWrite|QIODevice::Truncate);
    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);
    QAudioDeviceInfo info=QAudioDeviceInfo::defaultInputDevice();
    if(!info.isFormatSupported(format))
        format=info.nearestFormat(format);
    audioInput=new QAudioInput(format,this);
    audioInput->setBufferSize(4000);
    audioInput->start(&audioDevice);

    connect(&globalGameMsger::m,&globalGameMsger::gameBegin,this,&MainWindow::onGameBegin);
    connect(&globalGameMsger::m,&globalGameMsger::gameOver,this,&MainWindow::onGameOver);
    connect(&globalGameMsger::m,&globalGameMsger::gameRestart,this,&MainWindow::onGameRestart);

    player=new QMediaPlayer;
    player->setMedia(QUrl("qrc:/Sounds/plDead_poland.mp3"));
    player->setVolume(100);
}
MainWindow::~MainWindow()
{
    audioInput->stop();
    audioDevice.close();
    delete ui;
    delete player;
}
void MainWindow::paintEvent(QPaintEvent*)
{
    QPainter painter(this);
    scene.render(&painter);
}
void MainWindow::tick()
{
    emit update();

    qreal q=0;
    for(QVector<const short>::iterator it=audioDevice.data.begin();it!=audioDevice.data.end();++it)
    {
        int amp=abs(*it);
        q=amp*amp;
    }
    qreal mean=q/audioDevice.data.length(),volume;
    if(mean>=1)
        volume=10*log10(mean);
    else
        volume=0;
    //setWindowTitle(QString("Yelling %1").arg(volume));
    //if(volume>=35)
    //{
    //    emit globalGameMsger::m.jump((volume-35)/1.5);

    //}

        //emit globalGameMsger::m.jump((volume)/3);
        //emit globalGameMsger::m.onVoiceAmp(volume);

    std::vector<float>pitches=pyin.feed(audioDevice.dataF.toStdVector());
    if(!pitches.empty())
    {
        //emit globalGameMsger::m.jump(log2(pitches[0]/220)*12.0/3.0);
        //float noteCnt=12*log2(pitches[0]/220.0);
        //int noteToA3=roundf(noteCnt);
        int noteToA1=roundf(12*log2(pitches[0]/55.0));
        //int High=(noteToA3+9)/12+3;
        int High1=(noteToA1+9)/12+1;
        if(noteToA1>=0)
        {
            //if(running)
            //setWindowTitle(QString("Frequency %1Hz ; Volume %2").arg(pitches[0],6,'g').arg(log2(pitches[0]/220)*12.0/3.0));
            //setWindowTitle(QString("Frequency %1Hz ; Note %2 ; Volume %3").arg(pitches[0],6,'g').arg(QString("%1%2").arg(noteName[noteToA1%12]).arg(High1)).arg(volume));
            scene.setNote(QString("%1%2").arg(noteName[noteToA1%12]).arg(High1),Qt::white);
            scene.setNotePoint(30>volume*2.5?30:volume*2.5);
        }
        if(pitches[0]>220 && volume>=40)
        {
            emit globalGameMsger::m.controlByFrequencyAndVolume(pitches[0],volume);
            scene.setNoteCol(qRgb(255,0,0));
            scene.setNotePoint(volume*2.5);
        }
    }
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_S:
        if(scene.getstate()==BackGroundRollingScene::tagState::waiting)
        emit globalGameMsger::m.gameBegin(1);
        break;
    case Qt::Key_D:
        if(scene.getstate()==BackGroundRollingScene::tagState::waiting)
        emit globalGameMsger::m.gameBegin(2);
        emit globalGameMsger::m.jump(4);
        break;
    case Qt::Key_Space:
        emit globalGameMsger::m.jump(4);
        break;
    case Qt::Key_R:
        emit globalGameMsger::m.gameRestart();
        break;
    case Qt::Key_Shift:
        emit globalGameMsger::m.shiftPressed();
        break;
    case Qt::Key_Z:
        //emit globalGameMsger::m.ZPressed();
        break;
    }
}
void MainWindow::onGameBegin(int gamemode)
{
    if(gamemode==1)
    setWindowTitle("Say AHHHHHH!");
    if(gamemode==2)
    setWindowTitle("Press space and AHHHHHH!");
    running=1;
}
void MainWindow::onGameOver()
{
    file.setFileName("highScore.txt");
    file.open(QIODevice::ReadWrite);
    QTextStream inout(&file);
    int sc,score=scene.getScore();
    inout>>sc;
    inout.setDevice(&file);
    inout.seek(0);
    if(sc<score)
    {
        sc=score;
        inout<<sc;
    }
    setWindowTitle(QString("Game Over HighScore %1").arg(sc));
    file.close();
    running=0;
    player->play();
}
void MainWindow::onGameRestart()
{
    setWindowTitle("Press S or D to start");
    player->setMedia(QUrl("qrc:/Sounds/plDead_poland.mp3"));
}
